package com.tang4j.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tang4j.core.model.ResponseModel;
import com.tang4j.core.model.easyui.TreeGrid;
import com.tang4j.core.model.factory.ResponseModelFactory;
import com.tang4j.core.service.impl.AbstractServiceImpl;
import com.tang4j.mapper.ThSysDeptMapper;
import com.tang4j.model.ThSysDept;
import com.tang4j.model.factory.TreeGridFactory;
import com.tang4j.service.ThSysDeptService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author saber
 * @since 2019-11-21
 */
@Service
public class ThSysDeptServiceImpl extends AbstractServiceImpl<ThSysDeptMapper, ThSysDept> implements ThSysDeptService {
    @Override
    public ResponseModel getDeptTree() {
        try {
            List<TreeGrid> topDeptList = null;
            List<ThSysDept> thSysDeptList = this.queryList(new QueryWrapper<>());
            List<TreeGrid> byDeptList = TreeGridFactory.createByDept(thSysDeptList);
            Map<String, List<TreeGrid>> deptMap = byDeptList.stream()
                    .collect(Collectors.groupingBy(TreeGrid::getPId));
            topDeptList = deptMap.get("0");
            topDeptList.forEach(topDep -> {
                topDep.setChildren(deptMap.get(topDep.getId()));
                if (topDep.getChildren() != null) {
                    topDep.getChildren().forEach(childDept ->
                            childDept.setChildren(deptMap.get(childDept.getId())));
                }

            });
            return ResponseModelFactory.OKWithData(topDeptList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseModelFactory.error(e.getMessage());
        }
    }
}
